package com.demo.springBoot2.socket;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.demo.springBoot2.service.IUsersInfoService;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author pl711@qq.com
 * @PackageName springBoot2
 * @Package com.demo.springBoot2.config
 * @Date 2024/3/27 17:50
 * @Version 1.0
 */
@Component
//定义此类是WS的服务器端
@ServerEndpoint("/gift/{nickname}")
public class GiftSocketServer {
    private static Map<String,SocketUserInfo> map = new HashMap<>();
    //利用静态变量只会实例一次
    private static IUsersInfoService iUsersInfoService;
    /**
     * 连接建立成功时触发
     * @param session 当前会话
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("nickname")String nickname){
        SocketUserInfo s = new SocketUserInfo(nickname, session);
        map.put(nickname,s);
        System.out.println("成功的建立了连接");
    }
    /**
     * 连接关闭时触发
     */
    @OnClose
    public void onClose(@PathParam("name")String name){}
    /**
     * 收到客户端消息时触发
     * @param message
     */
    @OnMessage
    public void onMessage(String message ){
        //解析json
        JSONObject jsonObject = JSONUtil.parseObj(message);
        System.out.println(jsonObject);
        String text = jsonObject.getStr("text");
        String code = jsonObject.getStr("code");
        String nickname = jsonObject.getStr("nickname");

        JSONObject json1 = JSONUtil.createObj()
                .put("nickName", nickname)
                .put("text", text)
                .put("code", code);
        //单聊
        try {
            //通过session长连接隧道给前端推送信息
            map.get(nickname).getSession().getBasicRemote().sendText(json1.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发生错误时触发
     * @param error
     */
    @OnError
    public void onError(Throwable error,@PathParam("name")String name){}

}